/// <reference path="../../index.d.ts" />

var canvas;
var context;
var clockRadius;
var messagePortName = "TizenScreenCaptureMsgPort"; // Remote port name
var remoteAppId = "2lfUowOjEK.TizenCaptureService.dll"; // Target application's App ID

function displayResult(result) {
  const logBox = document.getElementById("log_box");
  const newElement = document.createElement("div");
  newElement.innerHTML = result;
  logBox.appendChild(newElement);
}

const bcName = {
  Default: "bc1",
  Cycle: "bc2",
  "Color Wheel": "bc3",
  Spotlight: "bc4",
};

var getDeviceInfo = "getDeviceInfo";

window.onload = function () {
  // Initialize canvas first
  // canvas = document.querySelector("canvas");
  // context = canvas.getContext("2d");
  // document.width = 600;
  // clockRadius = document.width / 2;

  // //Assigns the area that will use Canvas
  // canvas.width = document.width;
  // canvas.height = canvas.width;

  // Start the initialization process
  console.log("Initializing...");
  // initializeService();

  // add eventListener for keydown
  document.addEventListener("keydown", function (e) {
    switch (e.keyCode) {
      case 37: //LEFT arrow
        break;
      case 38: //UP arrow
        break;
      case 39: //RIGHT arrow
        break;
      case 40: //DOWN arrow
        break;
      case 13: //OK button
        break;
      case 10009: //RETURN button
        tizen.application.getCurrentApplication().exit();
        break;
      default:
        console.log("Key code : " + e.keyCode);
        break;
    }
  });

  //   setInterval(watch, 500);
};

// 请求接口
async function sendRequest(url, method = "GET", data = null) {
  const options = {
    method: method,
    headers: {
      "Content-Type": "application/json",
      // 如果需要认证，可以添加认证头
      // 'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    },
  };

  if (method === "POST" || method === "PUT") {
    options.body = JSON.stringify(data);
  }

  try {
    const response = await fetch(url, options);
    console.log("response", response);

    if (!response.ok) {
      throw new Error("Network response was not ok " + response.statusText);
    }
    return await response.json();
  } catch (error) {
    // console.error("请求报错", error);
    // message.error("请求报错" + error);
    throw error;
  }
}

function remapPanels(layout, orientation, screenWidth, screenHeight) {
  const marginX = screenWidth * 0.1;
  const marginY = screenHeight * 0.1;

  const panels = layout.positionData;
  const rotatedPositions = [];

  for (const panel of panels) {
    if (panel.shapeType === 12) {
      continue; // Skip the controller
    }
    const [rotatedX, rotatedY] = rotatePoint(panel.x, panel.y, orientation);
    rotatedPositions.push({ panelId: panel.panelId, rotatedX, rotatedY });
  }

  // Update bounds
  const min_x = Math.min(...rotatedPositions.map((pos) => pos.rotatedX));
  const max_x = Math.max(...rotatedPositions.map((pos) => pos.rotatedX));
  const min_y = Math.min(...rotatedPositions.map((pos) => pos.rotatedY));
  const max_y = Math.max(...rotatedPositions.map((pos) => pos.rotatedY));

  // Adjust scaling to fit within screen margins
  const scaleX = (screenWidth - 2 * marginX) / (max_x - min_x);
  const scaleY = (screenHeight - 2 * marginY) / (max_y - min_y);
  const scale = Math.min(scaleX, scaleY);

  const panelPositions = [];
  for (const { panelId, rotatedX, rotatedY } of rotatedPositions) {
    const newX = Math.round((rotatedX - min_x) * scale + marginX);
    const newY = Math.round((rotatedY - min_y) * scale + marginY);
    panelPositions.push({
      panelID: panelId,
      centroidX: newX,
      centroidY: newY,
    });
  }

  return panelPositions;
}

function rotatePoint(x, y, angleDeg) {
  const angleRad = -angleDeg * (Math.PI / 180); // Rotate clockwise
  const cosTheta = Math.cos(angleRad);
  const sinTheta = Math.sin(angleRad);
  const newX = x * cosTheta - y * sinTheta;
  const newY = x * sinTheta + y * cosTheta;
  return [newX, newY];
}

// 构造setMirrorConfig所需要的参数
function constructSetMirrorConfigParams(urls) {
  if (urls.length === 0) {
    return;
  }

  // 遍历ips去请求接口，使用promise.all
  const requests = urls.map(async (url) => {
    const response = await sendRequest(`${url}/`, "GET");
    return response;
  });

  return {
    mode: 0,
    devices: [
      {
        ip: "192.168.1.x",
        controlVersion: 2,
        shapeType: 2,
        scaleFactor: 1.0,
        panels: [
          {
            panelID: 1,
            centroidX: 100,
            centroidY: 100,
          },
        ],
      },
    ],
  };
}
